import { useState, useEffect } from 'react';
import {
  Box,
  Grid,
  Card,
  CardContent,
  CardMedia,
  CardActions,
  Typography,
  Button,
  IconButton,
  Pagination,
  Chip,
  CircularProgress,
  Alert,
} from '@mui/material';
import { Delete as DeleteIcon, Edit as EditIcon, Link as LinkIcon } from '@mui/icons-material';
import { PromotionService, Promotion } from '../services/PromotionService';
import { useAuth } from '../../auth/AuthContext';
import PromotionResourceForm from './PromotionResourceForm';

const getStatusColor = (status: string) => {
  switch (status) {
    case 'active':
      return 'success';
    case 'expired':
      return 'error';
    case 'upcoming':
      return 'warning';
    default:
      return 'default';
  }
};

const getStatusText = (status: string) => {
  switch (status) {
    case 'active':
      return '进行中';
    case 'expired':
      return '已结束';
    case 'upcoming':
      return '即将开始';
    default:
      return '未知';
  }
};

interface PromotionListProps {
  type?: 'all' | 'active' | 'effective';
  onEdit?: (promotion: Promotion) => void;
}

const PromotionList = ({ type = 'all', onEdit }: PromotionListProps) => {
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [pageSize] = useState(12);
  const [resourceFormOpen, setResourceFormOpen] = useState(false);
  const [selectedPromotionId, setSelectedPromotionId] = useState<string>('');
  
  const { user } = useAuth();

  const fetchPromotions = async () => {
    try {
      setLoading(true);
      setError(null);
      
      let response;
      switch (type) {
        case 'active':
          response = await PromotionService.getActivePromotions();
          setPromotions(response);
          setTotalPages(1);
          break;
        case 'effective':
          response = await PromotionService.getInProgressPromotions();
          setPromotions(response);
          setTotalPages(1);
          break;
        default:
          response = await PromotionService.getPromotionList(page, pageSize);
          setPromotions(response.promotions);
          setTotalPages(Math.ceil(response.total / pageSize));
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPromotions();
  }, [type, page]);

  const handleDelete = async (id: string) => {
    if (!window.confirm('确定要删除这个活动吗？')) return;
    
    try {
      await PromotionService.deletePromotion(id);
      fetchPromotions();
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除失败');
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" p={3}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ width: '100%' }}>
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3}>
        {promotions.map((promotion) => (
          <Grid item xs={12} sm={6} md={4} lg={3} key={promotion.id}>
            <Card>
              <CardMedia
                component="img"
                height="140"
                image={promotion.imageUrl || '/default-promotion.jpg'}
                alt={promotion.title}
              />
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
                  <Typography gutterBottom variant="h6" component="div" noWrap sx={{ flex: 1 }}>
                    {promotion.title}
                  </Typography>
                  <Chip
                    label={getStatusText(promotion.status)}
                    color={getStatusColor(promotion.status) as 'success' | 'error' | 'warning' | 'default'}
                    size="small"
                    sx={{ ml: 1 }}
                  />
                </Box>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                  {promotion.description}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  开始时间：{new Date(promotion.startTime).toLocaleString('zh-CN')}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  结束时间：{new Date(promotion.endTime).toLocaleString('zh-CN')}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  积分奖励：{promotion.points}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  创建者：{promotion.creatorName}
                </Typography>
              </CardContent>
              <CardActions sx={{ justifyContent: 'flex-end' }}>
                <IconButton
                  onClick={() => {
                    setSelectedPromotionId(promotion.id);
                    setResourceFormOpen(true);
                  }}
                  size="small"
                  title="管理关联资源"
                >
                  <LinkIcon />
                </IconButton>
                {user && (user.id === promotion.creatorId || user.role === 'admin') && (
                  <>
                    {onEdit && (
                      <IconButton
                        onClick={() => onEdit(promotion)}
                        size="small"
                        title="编辑"
                      >
                        <EditIcon />
                      </IconButton>
                    )}
                    <IconButton
                      onClick={() => handleDelete(promotion.id)}
                      size="small"
                      color="error"
                      title="删除"
                    >
                      <DeleteIcon />
                    </IconButton>
                  </>
                )}
              </CardActions>
            </Card>
          </Grid>
        ))}
        {promotions.length === 0 && (
          <Grid item xs={12}>
            <Typography variant="body1" color="text.secondary" align="center">
              暂无活动
            </Typography>
          </Grid>
        )}
      </Grid>

      {type === 'all' && totalPages > 1 && (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <Pagination
            count={totalPages}
            page={page}
            onChange={(_, value) => setPage(value)}
            color="primary"
          />
        </Box>
      )}

      <PromotionResourceForm
        open={resourceFormOpen}
        onClose={() => setResourceFormOpen(false)}
        promotionId={selectedPromotionId}
      />
    </Box>
  );
};

export default PromotionList;